<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="../js/vue.js"></script>
    <style>
        .active {
            background: #ff4400;
            color: #fff;
        }
    </style>
</head>

<body>
    <div id="app">
        <input type="text" v-model="kw" @keydown.down="down" @keydown.up.prevent="up" @keydown.enter="enter">
        <ul>
            <li v-for="(item,index) in arr" v-if="4>index" :key="item[0]" :class="index===n?'active':''">{{item[0]}}</li>
        </ul>
    </div>
    <script>
        // http://suggestion.baidu.com/su?cb=callback&wd=123
        let vm = new Vue({
                el: "#app",
                data: {
                    // 1.初始化数据
                    kw: "",
                    arr: [],
                    n: -1
                },
                watch: {
                    // 2.监听数据，并发请求
                    kw() {
                        if (this.kw === '') {
                            this.arr = []
                            return;
                        }
                        let os = document.createElement("script")
                            //os.src = `http://suggestion.baidu.com/su?cb=callback&wd=` + this.kw;
                        os.src = ` https://suggest.taobao.com/sug?q=${this.kw}&callback=callback&code=utf-8`
                            // https://suggest.taobao.com/sug?q=sk2&callback=aa&code=utf-8
                        document.body.appendChild(os)
                    }
                },
                methods: {
                    //下键
                    down() {
                        this.n++;
                        if (this.n >= 4) {
                            this.n = -1
                        }
                    },
                    //上键
                    up() {
                        this.n--;
                        if (this.n < 0) {
                            this.n = 4
                        }
                    },
                    //回车
                    enter() {
                        if (this.n >= 0 && this.n <= 3) {
                            window.open(` https://s.taobao.com/search?q=${ this.arr[this.n][0]}`, "_self")
                                // ` https://suggest.taobao.com/sug?q=${ this.arr[this.n]}&callback=aa&code=utf-8 `, "_self"
                        } else {
                            window.open(` https://s.taobao.com/search?q=${this.kw}`, "_self")

                        }

                    }
                }
            })
            // 3.处理数据 
        function callback(res) {
            console.log(res);
            vm.arr = res.result;
        }
    </script>
</body>

</html>